package no.ntnu.fp.handlers;

import java.io.IOException;

import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.AppointmentDeletedMessage;
import no.ntnu.fp.messages.impl.DeleteAppointmentMessage;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.services.AppointmentService;

public class DeleteAppointmentHandler implements Handler {
	private final AppointmentService appointmentService;
	
	public DeleteAppointmentHandler(AppointmentService appointmentService) {
		this.appointmentService = appointmentService;
	}

	@Override
	public void handleMessage(Message message) {
		DeleteAppointmentMessage deleteAppointmentMessage 
										= (DeleteAppointmentMessage) message;
		
		Appointment appointment = deleteAppointmentMessage.getAppointment();
		appointmentService.deleteAppointment(appointment);
		
		AppointmentDeletedMessage reply = new AppointmentDeletedMessage(appointment);
		
		Connection connection = ReceiveWorker.getThreadLocalConnection();
		
		try {
			connection.send(reply.toString());
		} catch (IOException ex) {
			throw new NetworkException("Could not send appointment " +
					"					deletion acknowledgement", ex);
		}
	}

}
